package com.gitee.sidihuo.platform.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 使用Redis缓存开关
 * 注意：更改默认值后，如果Redis重启会失效！！！
 */
@Slf4j
@Component
public class RedisConfigHelper {

    private static RedisFacade redisFacade;

    @Autowired(required = false)
    public void setRedisFacade(RedisFacade redisFacade) {
        RedisConfigHelper.redisFacade = redisFacade;
    }

    public static String getValue(String configKey, String defaultConfigValue) {
        String cache = redisFacade.getCache(configKey, true);
        if (cache != null && !StringUtils.equals(defaultConfigValue, cache)) {
            log.info("RedisConfigHelper defaultConfigValue need to fixed configKey = {}  defaultConfigValue = {} cacheCurrent = {}", configKey, defaultConfigValue, cache);
        }
        return cache == null ? defaultConfigValue : cache;
    }

    public static String setValue(String configKey, String configValue, int expireMinutes) {
        String cacheCurrent = redisFacade.getCache(configKey, false);
        String cacheNew = redisFacade.setCache(configKey, configValue, expireMinutes, TimeUnit.MINUTES, false);
        log.info("RedisConfigHelper setValue configKey = {} configValue {} -> {}", configKey, cacheCurrent, cacheNew);
        return cacheNew;
    }

    public static String setValueExpire20Days(String configKey, String configValue) {
        return setValue(configKey, configValue, 1440 * 20);
    }

    public static boolean isOpen(String switchKey, boolean isOpenDefault) {
        String value = getValue(switchKey, isOpenDefault ? "Y" : "N");
        return StringUtils.equals(value, "Y");
    }

    public static boolean setSwitchStatus(String switchKey, boolean isOpen, int expireMinutes) {
        String value = setValue(switchKey, isOpen ? "Y" : "N", expireMinutes);
        return StringUtils.equals(value, "Y");
    }

    public static boolean setSwitchStatusExpire20Days(String switchKey, boolean isOpen) {
        return setSwitchStatus(switchKey, isOpen, 1440 * 20);
    }


}
